import React from "react";
import _ from 'lodash';
import View from "../base/View";
import defaultData from "./data";
import { Map } from 'react-amap';
import classNames from 'classnames';
import { message } from 'antd';
import ThirdParty from '../../view/third-party';
import './index.less';

export default class MapView extends View {
  constructor(props) {
    super(props);

    this.state = {
      isFail: false,
      location: props.data.location,
      isSetCurrentCenter: props.data.isSetCurrentCenter
    };

    this.map = null;
    this.marker = null;
    this.placeSearch = null;
    this.geocoder = null;
    this.location = null;
    this.mapCenter = { longitude: 120, latitude: 30 };
    this.mapEvents = {
      created: (mapInstance) => {
        this.map = mapInstance;

        AMap.plugin(['AMap.PlaceSearch', 'AMap.Geocoder', 'AMap.Geolocation'], () => {
          this.placeSearch = new AMap.PlaceSearch();
          this.marker = new AMap.Marker();
          this.location = new AMap.Geolocation({
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000, //超过10秒后停止定位，默认：无穷大
            buttonPosition: 'RB',
            buttonOffset: new AMap.Pixel(10, 20), 
            zoomToAccuracy: true, //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          });

          this.setLocation(props.data.isSetCurrentCenter, props.data.location);
        });
      }
    }
  }

  componentDidMount() {
    this.thirdParty = new ThirdParty();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data.location !== this.state.location || nextProps.data.isSetCurrentCenter !== this.state.isSetCurrentCenter) {

      this.setLocation(nextProps.data.isSetCurrentCenter, nextProps.data.location);
      this.setState({ isSetCurrentCenter: nextProps.data.isSetCurrentCenter});
    }
  }

  onComplete = data => {
    const { formattedAddress } = data;

    if (formattedAddress) {
      this.getLocation(formattedAddress);
    }
  }

  onError = data => {
    message.error(data.message);
  }

  setLocation = (isSetCurrentCenter, location) => { // 设置定位位置
    if (isSetCurrentCenter) {
      this.thirdParty.excu('getCurrentLocation').then(res => {
        const { longitude, latitude } = res;

        this.getLocation([longitude, latitude]);
      }).catch(() => {
        this.location.getCurrentPosition(); 
        AMap.event.addListener(this.location, 'complete', this.onComplete); //返回定位信息
        AMap.event.addListener(this.location, 'error', this.onError);
      });
    } else {
      if (!!~location.indexOf(',')) {
        location = location.split(',');
        
        if (/[1-9]*\d*\.?\d*/.test(location[0]) && /[1-9]*\d*\.?\d*/.test(location[1])) {
          location = [location[0], location[1]];
        }
      }
  

      this.getLocation(location);
      this.setState({ location });
    }
  }

  getLocation = address => { //定位到设置的位置
    if (!this.placeSearch) return;

    this.setState({
      isFail: false
    });

    if (_.isArray(address)) {
      this.map.remove(this.marker);
      this.map.add(this.marker);
      this.marker.setPosition(address);
      this.map.setFitView(this.marker);

      this.setState({ isFail: false });
    } else {
      this.placeSearch.search(address, (status, result) => {
        if(status === 'complete' && result.info === 'OK') {
          this.map.remove(this.marker);
          this.map.add(this.marker);
          this.marker.setPosition(result.poiList.pois[0].location);
          this.map.setFitView(this.marker);

          this.setState({ isFail: false });
        } else {
          this.setState({
            isFail: true
          });
        }
      });
    }
  }

  renderContent() {
    const { isFail } = this.state;

    return (
      <div className='wea-edc-map-conatiner'>
        <Map ecId={`${this && this.props && this.props.ecId || ''}_Map@urnshs`} 
          zoom={5}
          jogEnable={false}
          animateEnable={false} 
          center={this.mapCenter} 
          events={this.mapEvents} 
        />
        <div className={classNames("fail-map", { hide: !isFail })}></div>
      </div>
    );
  }
}

MapView.defaultProps = {
  data: defaultData,
  value: ''
};